import React, { useState, useEffect } from 'react'
import { View } from '@tarojs/components'
import { AtTabBar, AtGrid } from 'taro-ui'
import { useRequest } from 'ahooks'
import { request, baseURL } from '../../utils/request'
import Taro, { useReachBottom, useDidShow } from '@tarojs/taro'
import styles from './index.module.less'

const valueMap = ['', 0, 1, 2]
const getGoods = (page: number, type: number | undefined) => {
  return request('get', '/app/mygoods', { page, size: 10, type })
}
const MyUsedList: React.FC<{}> = ({ }) => {
  const [tag, setTag] = useState(0)
  const [page, setPage] = useState(1)
  const [goods, setGoods] = useState({ total: 0, data: [] })
  const good = useRequest(getGoods, {
    manual: true,
    onSuccess: d => {
      setGoods({
        // @ts-ignore
        total: d.total, data: page === 1 ? d.data : [...goods.data, ...d.data]
      })
    }
  })
  const changeTags = (index: number) => {
    setTag(index)
    setGoods({ total: 0, data: [] })
    setPage(1)
    // @ts-ignore
    good.run(1, valueMap[index])
  }
  useReachBottom(() => {
    if (goods.total === goods.data.length) {
      Taro.showToast({
        title: "已全部加载",
        icon: 'none'
      })
      return
    }
    setPage(page + 1)
  })
  useEffect(() => {
    {/**@ts-ignore */ }
    good.run(page, valueMap[tag])
  }, [page])
  const goDetail = (id) => {
    Taro.navigateTo({
      url: `/pages/tinyused/usedDetail?id=${id}&has_delete=true`,
    })
    Taro.setNavigationBarTitle({
      title: "二手详情信息"
    })
  }
  useDidShow(() => {
    if (page > 1) {
      setPage(1)
    } else {
      good.refresh()
    }
  })

  const tabList = [{ title: '全部' }, { title: '商品' }, { title: '求购' }, { title: '失物招领' }]
  return (
    <View className={styles.list}>
      <AtTabBar
        tabList={tabList}
        onClick={changeTags}
        current={tag}
      />
      {/**@ts-ignore */}
      {goods.data && <AtGrid onClick={(w) => goDetail(w.id)} data={goods.data?.map(item => {
        {/**@ts-ignore */ }
        return { image: `${baseURL}/${item.picture}`, value: item.content, id: item.id }
      })} columnNum={2}></AtGrid>}
    </View>
  )
}

export default MyUsedList